package com.alameda.common.aop;

import com.alameda.common.result.Result;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import static com.alameda.common.base.constant.ProjectConstant.TRACE_ID;

/**
 * 接口日志链路跟踪aop
 *
 * @author Lv
 * @date 2024/7/2
 */
@Order(20)
@Aspect
@Component
public class ApiTraceAop {
    /**
     * 定义切点 扫描所有controller接口
     */
    @Pointcut("within(com.alameda.controller.v1..*Controller)")
    public void controllerPoint() {
    }

    /**
     * 后置处理
     *
     * @param joinPoint 切点对象
     * @param result    返回对象
     */
    @AfterReturning(pointcut = "controllerPoint()", returning = "result")
    public void afterControllerMethod(JoinPoint joinPoint, Object result) {
        if (result instanceof Result) {
            // 类型转换成功则设定链路id
            ((Result<?>) result).setTraceId(MDC.get(TRACE_ID));
        }
        // 释放内存
        MDC.remove(TRACE_ID);
    }
}
